home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
- From: Dan Pop <danpop@mail.cern.ch>
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Sat, 20 Jan 1996 02:25:46 +0100
- Organization: CERN European Lab for Particle Physics
- Message-ID: <9601200125.AA12574@dxmint.cern.ch>
- References: <4dorr8$i58@cloner3.netcom.com> <4dp5dk$t3r@newsbf02.news.aol.com>
- X-NNTP-Posting-Host: hpl3sn03.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
- X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
-
- babycox@aol.com (BabyCox) writes:
-
- >>#define ISPOW2(x) (((x) & 1) ^ 1)
- >
- >That will not work, it returns the next lowest MULTIPLE of two,
-
- Nope, it returns either 0 (for odd numbers) or 1 (for even numbers).
-
- >here's what I would do:
- >
- >Boolean IsPowerOfTwo(long x)
-
- There is no Boolean type in C.
-
- >{
- > for(short y = 0;y<=31;y++)
- ^^^^^
- This is a syntax error in C.
-
- > {
- > if (x = 1) return true;
- ^^^^^
- Are you sure that this is what you meant?
-
- > x >>= 1;
-
- The result of this expression is implementation-defined if x < 0.
-
- > }
- > return false;
- >}
-
- C doesn't define the "true" and "false" symbols.
-
- Now let's rewrite the function in proper C and have a look at it:
-
- int IsPowerOfTwo(unsigned long x)
- {
- short y;
-
- for (y = 0; y < 31; y++)
- {
- if (x == 1) return 1;
- x >>= 1;
- }
- return 0;
- }
-
- Unless I'm missing something, this function will return 1 whenever its
- argument is non-null and 0 when its argument is 0. A considerably faster
- way to implement it would be:
-
- #define IsPowerOfTwo(x) (!!(x))
-
- Needless to say, its name is very misleading and it doesn't solve the
- original poster's problem :-)
-
- Moral: keep untested advice for yourself. If you can't be bothered to test
- them, why should we be bothered to read them?
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-